package com.chris.homecare.components
{
	import feathers.controls.Button;
	import feathers.controls.LayoutGroup;
	import feathers.layout.HorizontalLayout;
	
	import starling.display.Quad;
	import starling.events.Event;
	
	public class StarRatting extends LayoutGroup
	{
		public var buttonsArray:Array;
		public var currentSelectedIndex:uint;
		private var _addListeners:Boolean = false;
		
		private var overlayQuad:Quad;
		
		public function StarRatting(addListeners:Boolean = true)
		{
			_addListeners = addListeners;
		}
		
		override protected function draw():void
		{
			super.draw();
			if(!_addListeners)
			{
				overlayQuad.width = this.width;
				overlayQuad.height = this.height;
			}
		}
		
		override protected function initialize():void
		{
			var layoutGroup:LayoutGroup = new LayoutGroup();
			var layout:HorizontalLayout = new HorizontalLayout();
			layout.gap = 10;
			layoutGroup.layout = layout;
			addChild(layoutGroup);
			
			buttonsArray = new Array();
			
			for(var i:int=0; i<5; i++)
			{
				var button:Button = new Button();
				button.nameList.add("start-ratings-btn");
				button.isToggle = true;
				if(_addListeners) button.addEventListener(Event.TRIGGERED, onButtonTrigger);
				layoutGroup.addChild(button);
				buttonsArray.push(button);
			}
			
			if(!_addListeners) 
			{
				overlayQuad = new Quad(40,40,0xffffff);
				overlayQuad.alpha = 0;
				addChild(overlayQuad);
			}
			super.initialize();
		}
		
		private function onButtonTrigger(event:Event):void
		{
			var btnIndex:int = buttonsArray.indexOf(event.target);
			
			for(var i:int=0; i<5; i++)
			{
				if(i < btnIndex) 
				{
					Button(buttonsArray[i]).isSelected = true;
					currentSelectedIndex = btnIndex+1;
				}
				
				else if(i > 0)
				{
					Button(buttonsArray[i]).isSelected = false;
				}
				
				else
				{
					currentSelectedIndex = 0;
				}
			}
		}
		
		public function setSelectedForNum(index:int):void
		{
			for(var i:int=0; i<5; i++)
			{
				if(i < index) 
				{
					Button(buttonsArray[i]).isSelected = true;
					currentSelectedIndex = i+1;
				}
					
				else if(i > 0)
				{
					Button(buttonsArray[i]).isSelected = false;
				}
					
				else
				{
					currentSelectedIndex = 0;
				}
			}
		}
	}
}